<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use think\Config;
use think\Validate;
use app\admin\model\Cart;
use app\admin\model\exchange\Ordergas;
use app\admin\model\exchange\Ordergoods;
use app\admin\model\exchange\Orderrecharge;
use app\admin\model\exchange\OrderGasInfo;
use app\admin\model\exchange\OrderGoodsInfo;
use app\admin\model\exchange\Order;
use app\admin\model\goods_manage\Goods;
use app\admin\model\gas\Gasset;
use app\admin\model\gas\Gasgun;
use app\admin\model\gas\Gasoil;
use Yeepay\Yop\Sdk\V1\YopConfig;
use Yeepay\Yop\Sdk\V1\YopRequest;
use Yeepay\Yop\Sdk\V1\YopRsaClient;
use Yeepay\Yop\Sdk\V1\Util\YopSignUtils;
use sandpay\HmPayClient;
use app\admin\model\Sandmerch;
use app\admin\model\system_config\Storeset;
use app\admin\model\UserDetail;
use app\common\model\StoreConfig;
use app\admin\model\station\Station;
use app\admin\model\Oilorder;
/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'getDiscount', 'gassubmit', 'third','wxlogin'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }

    /**
     * 会员中心
     */
    public function index()
    {
        $this->success('', ['welcome' => $this->auth->nickname]);
    }

    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @ApiMethod (POST)
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email    邮箱
     * @param string $mobile   手机号
     * @param string $code     验证码
     */
    public function register()
    {
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $email = $this->request->post('email');
        $mobile = $this->request->post('mobile');
        $code = $this->request->post('code');
        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if ($email && !Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $ret = Sms::check($mobile, $code, 'register');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        $ret = $this->auth->register($username, $password, $email, $mobile, []);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $avatar   头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio      个人简介
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->post('username');
        $nickname = $this->request->post('nickname');
        $bio = $this->request->post('bio');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if ($username) {
            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Username already exists'));
            }
            $user->username = $username;
        }
        if ($nickname) {
            $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Nickname already exists'));
            }
            $user->nickname = $nickname;
        }
        $user->bio = $bio;
        $user->avatar = $avatar;
        $user->save();
        $this->success();
    }

    /**
     * 修改邮箱
     *
     * @ApiMethod (POST)
     * @param string $email   邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->post('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    /**
     * 第三方登录
     *
     * @ApiMethod (POST)
     * @param string $platform 平台名称
     * @param string $code     Code码
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->post("platform");
        $code = $this->request->post("code");
        $config = get_addon_config('third');
        $store_no = $this->request->post("store_no");
        $storeinfo = Storeset::where('store_no',$store_no)->find();
        if (!$config || !$storeinfo || !isset($storeinfo['wx_appid']) || empty($storeinfo['wx_appid'])) {
            $this->error(__('Invalid parameters'));
        }
        $agent_id = $storeinfo['agent_id'];
        $config[$platform]['app_id'] = $storeinfo['wx_appid'];
		$config[$platform]['app_secret'] = $storeinfo['wx_app_secret'];
		
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        
        if ($result) {
        	$result['store_no'] = $store_no;
        	$result['agent_id'] = $agent_id;
            $loginret = \addons\third\library\Service::connect($platform, $result);
  
            if ($loginret) {
                $data = [
                    'userinfo'  => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }
    
        /**
     * 第三方登录
     *
     * @ApiMethod (POST)
     * @param string $platform 平台名称
     * @param string $code     Code码
     */
    public function wxlogin()
    {
        $url = url('user/index');
        $platform = $this->request->post("platform");
        $code = $this->request->post("code");
        $iv = $this->request->post("iv");
        $encryptedData = $this->request->post("encryptedData");
        $store_no = $this->request->post("store_no");
        $config = get_addon_config('third');
        $storeinfo = Storeset::where('store_no',$store_no)->find();

        if (!$config || !$storeinfo || !isset($storeinfo['wx_appid']) || empty($storeinfo['wx_appid'])) {
            $this->error(__('Invalid parameters'));
        }
        $agent_id = $storeinfo['agent_id'];
        $config[$platform]['app_id'] = $storeinfo['wx_appid'];
		$config[$platform]['app_secret'] = $storeinfo['wx_app_secret'];
		
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getWxUserInfo(['code' => $code,'iv' => $iv,'encryptedData' => $encryptedData]);
//        $userinfo = [
//                  'mobile'  => "18650815930",
//                  'username' => "18650815930",
//                  'nickname'    => "18650815930",
//                  'avatar'        => "",
//              ];
//
//      $result = [
//                  'access_token'  => "52brih0MSMNFqr8UpxP0ww==",
//                  'refresh_token' => "",
//                  'expires_in'    => 0,
//                  'openid'        => "ovr9i4yBLu5mI--pgxqgOvuLsNlc",
//                  'unionid'       => "",
//                  'userinfo'      => $userinfo,
//                  'store_no'      => 1,
//              ];

        if ($result) {
        	$result['store_no'] = $store_no;
        	$result['agent_id'] = $agent_id;
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo'  => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }


    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function resetpwd()
    {
        $type = $this->request->post("type");
        $mobile = $this->request->post("mobile");
        $email = $this->request->post("email");
        $newpassword = $this->request->post("newpassword");
        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('Password must be 6 to 30 characters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }
     /**
     * 插入购物车
     *
     * @ApiMethod (POST)
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function insertCart()
    {
    	$user = $this->auth->getUser();
//      $user_id = $this->request->post("user_id");
        $goods_id = $this->request->post("goods_id");
        $num = $this->request->post("num");
        $store_no= $this->request->post("store_no");
        
        $co = Cart::where('goods_id',$goods_id)->where('store_no',$store_no)->where('user_id',$user->id)->find();
        if($co)
        {
        	Cart::where('id', $co['id'])->setInc('num', $num);
        	$this->success('操作成功');
        }
        
        Cart::create([
            'goods_id' => $goods_id,
            'store_no' => $store_no,
            'user_id' =>$user->id,
            'num' =>$num,
        ]);
        
        $this->success('操作成功');
    }
    
        /**
     * 购物车数量增减
     *
     * @ApiMethod (POST)
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function setnum()
    {
    	$user = $this->auth->getUser();
//  	$user_id = $this->request->post("user_id");
        $type = $this->request->post("type");
        $goods_id = $this->request->post("goods_id");
        $num = $this->request->post("num");
        $store_no= $this->request->post("store_no");
        
        $co = Cart::where('goods_id',$goods_id)->where('store_no',$store_no)->where('user_id',$user->id)->find();
        
        if($co)
        {
        	if($type == 1)Cart::where('id', $co['id'])->setInc('num', $num);
        	if($type == 2)
        	{
        		
        		Cart::where('id', $co['id'])->setDec('num', $num);
        		if(($co['num']-$num)<=0)
        			{
        				Cart::where('goods_id',$goods_id)->where('store_no',$store_no)->where('user_id',$user->id)->delete();
        			}
        	}
        	$this->success('操作成功');
        }
        if($type == 1)
        {
        	Cart::create([
	            'goods_id' => $goods_id,
	            'store_no' => $store_no,
	            'user_id' =>$user->id,
	            'num' =>$num,
	        ]);
        }
        
        
        $this->success('操作成功');
    }
         /**
     * 会员登录接口
     *
     */
    public function getuserinfo()
    {
        $user = $this->auth->getUser();
        $store_no = $this->request->post("store_no");
        $detail = UserDetail::where('store_no',$store_no)->where('id', $user->id)->find();
        $this->success('请求成功',$detail);
    }
    
      /**
     * 获取购物车数据
     *
     * @ApiMethod (POST)
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function getCart()
    {
    	$user = $this->auth->getUser();
//  	$user_id = $this->request->post("user_id");
        $store_no = $this->request->post("store_no");
 
        
        $cartlist = Cart::where('store_no',$store_no)->where('user_id',$user->id)->select();
        foreach ($cartlist as $index => $item) {
    		$item['detail'] = \app\admin\model\goods_manage\Goods::where('id', $item['goods_id'])->find();
    	}
        
        $this->success('操作成功',$cartlist);
    }
    
               /**
     * 订单列表
     *
     */
    public function orderlist()
    {
    	$user = $this->auth->getUser();
    	$type = $this->request->post('type');//1 充值  2加油  3 商品
//  	$user_id = $this->request->post('user_id');
    	$store_no = $this->request->post('store_no');
    	
    	$order_list = [];
    	
    	if($type == 1)
    	{
    		$order_list = Orderrecharge::where('store_no', $store_no)->where('user_id', $user->id)->where('is_pay', 1)->where('is_delete', 0)->select();
    	}
    	
    	if($type == 2)
    	{
    		$order_list = Ordergas::where('store_no', $store_no)->where('user_id', $user->id)->where('is_pay', 1)->where('is_delete', 0)->select();
    	}
    	
    	if($type == 3)
    	{
    		$order_list = Ordergoods::where('store_no', $store_no)->where('user_id', $user->id)->where('is_pay', 1)->where('is_delete', 0)->select();
    	}

    	foreach ($order_list as $index => $item) {
    		if($type == 2)
    	    {
    	    	$gaslist = OrderGasInfo::where('order_id', $item['id'])->select();
    	    	foreach ($gaslist as $in => $it) {
    	    		$gasgun = Gasgun::where('id', $it['gas_gun_id'])->find();
    	    		$gasset = Gasset::where('id', $gasgun['gas_id'])->find();
    	    		
    	    		$it['gunname'] = $gasgun['name'];
    	    		$it['gas_name'] = $gasset['gas_name'];
    	    	}
    	    	
    	    	$item['detail'] = $gaslist;
    	    }
    	    if($type == 3)
    	    {
    	    	$goodslist = OrderGoodsInfo::where('order_id', $item['id'])->select();
    	    	foreach ($goodslist as $in => $it) {
    	    		$it['info'] = Goods::where('id', $it['goods_id'])->find();
    	    	}
    	    	
    	    	$item['detail'] = $goodslist;
    	    }
    		
    	}
    	
    	$this->success('操作成功',$order_list);
    }
    
               /**
     * 油品提交订单
     *
     */
    public function gassubmit()
    {
     	$user = $this->auth->getUser();
//      $user_id = $this->request->post('user_id');
        $store_no = $this->request->post('store_no');
    	$num = 0;
    	$total_amount = $this->request->post('total_amount');//订单总额
    	$pay_type = $this->request->post('pay_type');
    	$gas_id = $this->request->post('gas_id');
    	$gas_gun_id = $this->request->post('gas_gun_id');
    	$pay = 1;
    	if($pay_type == 'balance')$pay = 5;
    	$total_price = $total_amount;
    	$discount_price = 0;
    	$timebool = true;
    	$llimitoil = StoreConfig::where('name','oil')->where('store_no',$store_no)->find();
    	$llimittime = StoreConfig::where('name','oil_times')->where('store_no',$store_no)->find();
    	$storeset = StoreConfig::where('name','awardoil')->where('store_no',$store_no)->find();
    	$limituser = StoreConfig::where('name','user_nolimit')->where('store_no',$store_no)->find();
    	$is_setcou = StoreConfig::where('name','is_setcou')->where('store_no',$store_no)->find();
        $coupon_type = StoreConfig::where('name','coupon_type')->where('store_no',$store_no)->find();
    	if(!empty($llimitoil['value'])&&$is_setcou['value'] == 1)
    	{
    		$oilarr = explode(',',$llimitoil['value']);
    		$amount = json_decode($storeset['value'],true);
    		$userarr = explode(',',$limituser['value']);
    		if(!empty($llimittime['value']))
    	    {
    	    	$limittime =  strtotime('-'.$llimittime['value'].' hours');
    	    	$is_order = Ordergas::where('createtime','>',$limittime)->where('is_pay',2)->where('user_id',$user->id)->where('discount_price','>',0)->where('store_no',$store_no)->count();
    	        if($is_order)$timebool = false;
    	      
    	    }
    	    if(in_array($user->id,$userarr))
	    	{
	    		$timebool = true;
	    	}
    		if(in_array($gas_id,$oilarr)&&!empty($amount)&&$timebool)
    		{
    			if($coupon_type['value']==1)
    			{
    				foreach ($amount as $k => $v) {
		    			if($total_amount >=$k&&$discount_price<$v)$discount_price = $v;
		    		}
    			}
    			
	    		if($coupon_type['value']==2)
    			{
	    		
		    		$amco = count($amount);
	    			$oil = \app\admin\model\gas\Gasset::where('id',$gas_id)->find();
	    			//升数
	    			$num = round($total_amount/$oil['price'],2);
	    			$i = 1;
	    			$boins = 0;
	    			$kamount = 0;
	    			foreach ($amount as $k => $v) {
//	    				if($amco == 1&&$total_amount>=$k)$discount_price = round($num*$v,2);
//		    			if($amco > 1)
//		    			{
//		    				if($i==1&&$total_amount<$k)break;
//		    				if($i>1&&$total_amount>=$k)
//		    				{
//		    					if($i == 2)$fnum = round($k/$oil['price'],2);
//		    					if($i > 2)$fnum = round(($k-$kamount)/$oil['price'],2);	
//		    					$fprice = round($fnum*$boins,2);
//		    					$discount_price = $discount_price + $fprice;
//		    					
//		    					if($amco == $i)
//		    					{
//		    						$fnum = round(($total_amount-$k)/$oil['price'],2);	
//			    					$fprice = round($fnum*$v,2);
//			    					$discount_price = $discount_price + $fprice;
//		    					}
//		    				}
//		    				
//		    				if($i>2&&$total_amount<$k)
//		    				{
//		    						$fnum = round(($total_amount-$kamount)/$oil['price'],2);
//		    						$fprice = round($fnum*$boins,2);
//		    						$discount_price = $discount_price + $fprice;
//		    						break;
//		    				}
//		    				
//		    				if($i==2&&$total_amount<$k)
//		    				{
//		    						$fnum = round($total_amount/$oil['price'],2);
//		    						
//		    						$fprice = round($fnum*$boins,2);
//		    						$discount_price = $discount_price + $fprice;
//		    						break;
//		    				}
//		    			}
		    			if($total_amount >=$k)$discount_price = round($num*$v,2);
		    		}
			    }
	    		
	    		
	    		
	    		if($discount_price>0)$total_amount = round($total_amount-$discount_price,2);
    		}
    	
    	}

//  	return 222;
//  	$storeset = StoreConfig::where('name','awardoil')->where('store_no',$store_no)->find();
//  
//  	$amount = json_decode($storeset['value'],true);
//  	if(!empty($amount))
//  	{
//  		foreach ($amount as $k => $v) {
//  			if($total_amount >=$k&&$discount_price<$v)$discount_price = $v;
//  		}
//  	}
//      if($discount_price>0)$total_amount = round($total_amount-$discount_price,2);
        
    	$osn = date('YmdHis') . rand(10000000,99999999);
    	$oil = Gasset::where('id',$gas_id)->find();
    		if(!$oil)$this->error('油号不存在');
//  		$paramgas['agent_id']=1;
	        $paramgas['store_no']=$store_no;
	        $paramgas['user_id']=$user->id;
	        $paramgas['order_no']=$osn;
	        $paramgas['total_price']=$total_price;
	        $paramgas['total_pay_price']=$total_amount;
	        $paramgas['discount_price']=$discount_price;
	        $paramgas['is_pay']=0;
	        $paramgas['pay_type']=$pay;
	        $paramgas['pay_way']=1;
	        $paramgas['pay_time']=time();
	        $paramgas['source_type']=1;
    		$resultgas = Ordergas::create($paramgas);
    		if($resultgas)
    		{
    			$num = round($total_amount/$oil['price'],2);
    			//订单详情
//  			$paraminfo['agent_id']=1;
		        $paraminfo['store_no']=$store_no;
		        $paraminfo['order_id']=$resultgas['id'];
		        $paraminfo['gas_gun_id']=$gas_gun_id;
		        $paraminfo['num']=$num;
		        $paraminfo['unit_price']=$oil['price'];
		        $paraminfo['total_price']=$total_price;
		        $paraminfo['unit']=$oil['unit'];

	    		$resultinfo = OrderGasInfo::create($paraminfo);
	    		
	    		//扣减油品库存
	    		$gun = Gasgun::where('id',$gas_gun_id)->find();
	    		Gasoil::where('id', $gun['oil_id'])->setDec('oil_num', $num);
	    		//录入总订单
//	    		$params['agent_id']=1;
		        $params['store_no']=$store_no;
		        $params['user_id']=$user->id;
		        $params['order_no']=$osn;
		        $params['total_price']=$total_price;
		        $params['total_pay_price']=$total_amount;
		        $params['discount_price']=$discount_price;
		        $params['is_pay']=0;
		        $params['pay_type']=$pay;
		        $params['type']=2;
		        $params['source_type']=1;
		        $params['pay_time']=time();
		        $params['pay_way']=1;
		    
		    	$result = Order::create($params);

    		}
      
    	
    	if($pay_type == 'balance')
    	{
    		if($total_amount > $user->money)$this->error('余额不足');
    		
    		   	$before = $user->money;
		    	$money = $user->money - $total_amount;
		    	$user->money = $money;
                $user->save();
                $memo = $oil['gas_name'];
                //写入日志
                $resultmo = \app\common\model\MoneyLog::create(['user_id' => $user->id, 'money' => $total_amount, 'before' => $before, 'after' => $money, 'memo' => $memo]);
		    	Order::where('order_no', $osn)->update(['is_pay'=>2]);
		    	Ordergas::where('order_no', $osn)->update(['is_pay'=>2]);
		    	$this->success('支付成功');
    		
    	}
    	
    	if($pay_type == 'wechat')
    	{
    		$storeinfo = \app\admin\model\system_config\Storeset::where('store_no',$store_no)->find();
    		$pay= \app\admin\model\payment\Payway::where('code','wechat')->find();
    		$channel= \app\admin\model\payment\Channel::where('id',$pay['channel_id'])->find();
    		$yee= \app\admin\model\Yee::where('store_no',$store_no)->find();
    		$userinfo= \app\admin\model\Third::where('user_id',$user->id)->find();
    	
    		if($channel['code'] == 'YeeBao')
    		{
    			  /*商户私钥*/
			        $private_key ="MIIEugIBADANBgkqhkiG9w0BAQEFAASCBKQwggSgAgEAAoIBAQCQMqL/T97RhAophQNRzBwE+vU+59PzfkEzyLZwMaQTduHvdTl4fg6KZ6ATFUgECI2JLpZq3cyjVYSlM9H20bRpZSaoYmsYyNibpf2lg+bMg9G+bS6elHvFn0ZJ+aU40wyWqPjtdLB9JYLDbLVsb6SzHegWovWeWD7vUqCbPhDK24V///baX2zV4609kfa1iBGbynF/0nggHw3leeUW9F8E8twSEF15ObE8ShywOMvi578kv9PUNmSiq8gfc/t8dWVOzi4mbDje49MhxMbuopGv1kcvHBrThTeqQ2plhQSs63AbwLpe4WsZbcNvG9zpjuci8bK1+Zb/3DnkmT4zEu6FAgMBAAECggEAHsQfEPhaoztX67nslmRFSi69atmN2HMEuGbHvjJpPpnr5OqPA41pztADUG8G+Y1VnYJqJ40BX4wcjB79Wnst0hr53414KkaYKMWG0+zLrrElbErhWoZ1zhmIprn0LaaiFfchfZCbI2iAeO/V2bgMXQcxgLruSwWrD+cCS303mgBgW7tWsqlfplLvtWqJBWyA4Y8ObV/RUuLjr38Q8nCGZ81ep+De0euDkV4JQ/tg7uQEvEAOwpB6EEBwYt8GZVwcq8SWfP1cOw0Q7hkvn+rHvnXa2MHg8pdQHOfigvHr4Z5udkSiM885Pbjyh6H+UldtKFx2pW9EoD4t37CMwjeJtQKBgQDMWc00sfln9lRUBarV0D7fL6Z8/kueyBaTXFrzauHGwqK9KvB9ADmqFuBxZij8fJBkQyQtgNgbutTqgo0BJgTB2Q5lH097SBUdrTUrJdo3+rKY4/fbQBU7zF9oQ2p+dyFHmW/zjjWALnQYchd1lsZGkrSg2qPto/PRttkES/jrywKBgQC0pLrjcQ+6XZAUie+wSML+f/zGvxw1821Tn8poe0FIaX7/vPhRo028eF+R4Kav/yiVxeTAzk1D5OtN0Q3XO/nIY6f68WbdjBeFFSyovpPi1GX8kSys5wIo79nNnF/cEIJMTnvmyn51RaH8jtSVhshqqzHdesezXTYV3lwg4Urk7wKBgFqKS0ZWuIdcd76GiEuVqdWfOifVT9H5Gy+NUurY51H2OL6RwN3RdLssyaLUvcIoup0BtozGsnmOzPlegHUK0D7HGf6p4cBgjqKIdK86ZTY6SFk/YDjvarkE8xyyCgQgaklb7WM/FetGKcAPBN/fvtfT9l3yoYEQDF5Vok+qDY8DAn80N2nOVOA2/tSnGzgtvNqgtl5bFOMStUrk4Uug5//27ofHZNhiwNG3qRP3FvkX5qnUoV9+XCP5fDKIS+W0UaHiSuxDnYQehmBGF9jQ7kXRS5Qvbcd8M0psiuhqhsku05bWd9lY3S+wtnAckSziDBPiwZmoa9VOA6Oerqfy2SzNAoGAETFFK7YKO6+fGNJv5M5KJuZsOGkqgmfkJhAOnC2wLPDMMFDXnWG+oPcI6bosyvM+I8FDqwE3VcbmFlEJPnC4hQvwK3JjAju6FGhDgoB98rihcaUlsJfoTvrSmkLAmQOH8DW+a0UVbcCMp7TtWgpC8UMT0adAb/4ngQhjYuED4pI=";
			
			        $request = new YopRequest("app_10088909942", $private_key);
			        $expireTime = date("yyyy-MM-dd HH:mm:ss", strtotime("+30 minute"));//过期时间
			        $client_ip = $_SERVER['REMOTE_ADDR'];
			        //加入请求参数
			        $request->addParam("parentMerchantNo",'10088970121');
			        $request->addParam("merchantNo",$yee['merchantNo']);
			        $request->addParam("orderId",$osn);
			        $request->addParam("orderAmount",$total_amount);
			        $request->addParam("expiredTime",$expireTime);
			        $request->addParam("notifyUrl",'https://store.leyinshuke.com/api/index/yeenotify');
			        $request->addParam("memo",'');
			        $request->addParam("goodsName",$oil['gas_name']);
			        $request->addParam("fundProcessType",'');
			        $request->addParam("payWay",'MINI_PROGRAM');
			        $request->addParam("channel", 'WECHAT');
			        $request->addParam("scene", 'OFFLINE');
			        $request->addParam("appId", $storeinfo['wx_appid']);
			        $request->addParam("userId",$userinfo['openid']);
			        $request->addParam("userIp", $client_ip);
			//      //提交Post请求
			        $response = YopRsaClient::post("/rest/v1.0/aggpay/pre-pay", $request);
			        if(isset($response->result->code) && $response->result->code == '00000')
			        {
			        	$data = json_decode($response->result->prePayTn, JSON_UNESCAPED_UNICODE);
			        	Order::where('order_no', $osn)->update(['channel'=>'YeeBao']);
		    	        Ordergas::where('order_no', $osn)->update(['channel'=>'YeeBao']);
			        	$this->success($response->result->message,$data);
			        }
                    $this->error('支付失败');
    		}
    		
    		if($channel['code'] == 'sandPay')
    		{
    			    $sandmer = Sandmerch::where('store_no',$store_no)->find();
    			    $request = new HmPayClient();

			        $url = $request->gatewayUrl;
			
			        $appId = '552021071325659';
			        $subAppId = $sandmer['sub_merchant_no'];
			        $method = "trade.create";
			        $format = $request->format;
			        $charset = $request->charset;
			        $signType = $request->signType;
			        $version = $request->apiVersion;
			        $timestamp = date("Y-m-d h:i:s");
			        $nonce = $request->getRandStr(8);
			        $privateKey = $request->rsaPrivateKey;
			        //支付方式
			        $payWay = "WECHAT";
			        $pay_type = "JSAPI";
			        $createIp = $_SERVER['REMOTE_ADDR'];//生产环境使用真实ip
			        $createTime = date("YmdHis");
			        $expireTime = date("YmdHis", strtotime("+10 minute"));//过期时间
			        $totalAmount = $total_amount;
			        $outOrderNo = $osn;
			        //商品详情 -- 按实际填写 或不填不上送
			        $goodsDetail1 = array();
			        $goodsDetail1['goods_id'] = $oil['id'];
			        $goodsDetail1['goods_name'] = $oil['gas_name'];
			        $goodsDetail1['price'] = $oil['price'];
		
			        $goodsDetail = array($goodsDetail1);
			        //订单详情
			        $body = $oil['gas_name'];
			        //商户交易门店
			        $storeId = $sandmer['sand_store_no'];
			        $mer_app_id = $storeinfo['wx_appid'];
			        $mer_buyer_id = $userinfo['openid'];
			        //终端信息
//			        $deviceInfo = array();
//			        $deviceInfo['longitude'] = '121.506377';
//			        $deviceInfo['latitude'] = '31.245105';
//			
			        $notifyUrl = 'https://store.leyinshuke.com/api/index/sandscannotify';
			
			        $bizContent = $request->tradecreate($payWay, $pay_type, $mer_app_id, $mer_buyer_id, $createIp, $createTime, $expireTime, $totalAmount, $outOrderNo, $goodsDetail, $body, $storeId, $notifyUrl);
			        
			        $response = $request->execute($url, $request->request($appId, $subAppId, $method, $format, $charset, $signType, $timestamp, $nonce, $version, $bizContent, $privateKey));
			        
			        $jsonResp = json_decode($response, JSON_UNESCAPED_UNICODE);
			        if(isset($jsonResp['code']) && $jsonResp['code'] == '200')
			        {
			        	$data = json_decode($jsonResp['data'], JSON_UNESCAPED_UNICODE);
			            $datapay = json_decode($data['pay_data'], JSON_UNESCAPED_UNICODE);
			            Order::where('order_no', $osn)->update(['channel'=>'sandPay']);
		    	        Ordergas::where('order_no', $osn)->update(['channel'=>'sandPay']);
			            $this->success($data['sub_msg'],$datapay);
			        }
		            $this->error('支付失败');
    		}
    	}
    	
    	
    	$this->error('支付失败');
    }
    
    
            /**
     *充值
     * 提交订单
     *
     */
    public function rechangesubmit()
    {
     	$user = $this->auth->getUser();
        $user_id = $this->request->post('user_id');
        $store_no = $this->request->post('store_no');
    	$total_amount = $this->request->post('total_amount');//订单总额
    	$pay_type = $this->request->post('pay_type');
    	$pay = 1;
    	if($pay_type == 'balance')$pay = 5;
    	$gift_amount = 0;
    	$storeset = StoreConfig::where('name','rechange')->where('store_no',$store_no)->column("value");
    	$recharge = json_decode($storeset,true);
    	if(!empty($recharge))
    	{
    		foreach ($recharge as $k => $v) {
    			if($total_amount >=$k&&$gift_amount<$v)$gift_amount = $v;
    		}
    	}


    	$osn = date('YmdHis') . rand(10000000,99999999);
//  	$oil = Gasset::where('id',$gas_id)->find();
//  		if(!$oil)$this->error('油号不存在');
//  		$paramgas['agent_id']=1;
	        $paramgas['store_no']=$store_no;
	        $paramgas['user_id']=$user->id;
	        $paramgas['order_no']=$osn;
	        $paramgas['total_price']=$total_amount;
	        $paramgas['total_pay_price']=$total_amount;
	        $paramgas['discount_price']=0;
	        $paramgas['gift_amount']=$gift_amount;
	        $paramgas['is_pay']=0;
	        $paramgas['pay_type']=$pay;
	        $paramgas['pay_way']=1;
	        $paramgas['pay_time']=time();
	        $paramgas['source_type']=1;
    		$resultgas = Orderrecharge::create($paramgas);
    		if($resultgas)
    		{

	    		//录入总订单
		        $params['store_no']=$store_no;
		        $params['user_id']=$user->id;
		        $params['order_no']=$osn;
		        $params['total_price']=$total_amount;
		        $params['total_pay_price']=$total_amount;
		        $params['discount_price']=0;
		        $params['gift_amount']=$gift_amount;
		        $params['is_pay']=0;
		        $params['pay_type']=$pay;
		        $params['type']=1;
		        $params['source_type']=1;
		        $params['pay_time']=time();
		        $params['pay_way']=1;
		    
		    	$result = Order::create($params);

    		}

    	
    	if($pay_type == 'wechat')
    	{
    		$storeinfo = \app\admin\model\system_config\Storeset::where('store_no',$store_no)->find();
    		$pay= \app\admin\model\payment\Payway::where('code','wechat')->find();
    		$channel= \app\admin\model\payment\Channel::where('id',$pay['channel_id'])->find();
    		$yee= \app\admin\model\Yee::where('store_no',$store_no)->find();
    		$userinfo= \app\admin\model\Third::where('user_id',$user->id)->find();
    	
    		if($channel['code'] == 'YeeBao')
    		{
    			  /*商户私钥*/
			        $private_key ="MIIEugIBADANBgkqhkiG9w0BAQEFAASCBKQwggSgAgEAAoIBAQCQMqL/T97RhAophQNRzBwE+vU+59PzfkEzyLZwMaQTduHvdTl4fg6KZ6ATFUgECI2JLpZq3cyjVYSlM9H20bRpZSaoYmsYyNibpf2lg+bMg9G+bS6elHvFn0ZJ+aU40wyWqPjtdLB9JYLDbLVsb6SzHegWovWeWD7vUqCbPhDK24V///baX2zV4609kfa1iBGbynF/0nggHw3leeUW9F8E8twSEF15ObE8ShywOMvi578kv9PUNmSiq8gfc/t8dWVOzi4mbDje49MhxMbuopGv1kcvHBrThTeqQ2plhQSs63AbwLpe4WsZbcNvG9zpjuci8bK1+Zb/3DnkmT4zEu6FAgMBAAECggEAHsQfEPhaoztX67nslmRFSi69atmN2HMEuGbHvjJpPpnr5OqPA41pztADUG8G+Y1VnYJqJ40BX4wcjB79Wnst0hr53414KkaYKMWG0+zLrrElbErhWoZ1zhmIprn0LaaiFfchfZCbI2iAeO/V2bgMXQcxgLruSwWrD+cCS303mgBgW7tWsqlfplLvtWqJBWyA4Y8ObV/RUuLjr38Q8nCGZ81ep+De0euDkV4JQ/tg7uQEvEAOwpB6EEBwYt8GZVwcq8SWfP1cOw0Q7hkvn+rHvnXa2MHg8pdQHOfigvHr4Z5udkSiM885Pbjyh6H+UldtKFx2pW9EoD4t37CMwjeJtQKBgQDMWc00sfln9lRUBarV0D7fL6Z8/kueyBaTXFrzauHGwqK9KvB9ADmqFuBxZij8fJBkQyQtgNgbutTqgo0BJgTB2Q5lH097SBUdrTUrJdo3+rKY4/fbQBU7zF9oQ2p+dyFHmW/zjjWALnQYchd1lsZGkrSg2qPto/PRttkES/jrywKBgQC0pLrjcQ+6XZAUie+wSML+f/zGvxw1821Tn8poe0FIaX7/vPhRo028eF+R4Kav/yiVxeTAzk1D5OtN0Q3XO/nIY6f68WbdjBeFFSyovpPi1GX8kSys5wIo79nNnF/cEIJMTnvmyn51RaH8jtSVhshqqzHdesezXTYV3lwg4Urk7wKBgFqKS0ZWuIdcd76GiEuVqdWfOifVT9H5Gy+NUurY51H2OL6RwN3RdLssyaLUvcIoup0BtozGsnmOzPlegHUK0D7HGf6p4cBgjqKIdK86ZTY6SFk/YDjvarkE8xyyCgQgaklb7WM/FetGKcAPBN/fvtfT9l3yoYEQDF5Vok+qDY8DAn80N2nOVOA2/tSnGzgtvNqgtl5bFOMStUrk4Uug5//27ofHZNhiwNG3qRP3FvkX5qnUoV9+XCP5fDKIS+W0UaHiSuxDnYQehmBGF9jQ7kXRS5Qvbcd8M0psiuhqhsku05bWd9lY3S+wtnAckSziDBPiwZmoa9VOA6Oerqfy2SzNAoGAETFFK7YKO6+fGNJv5M5KJuZsOGkqgmfkJhAOnC2wLPDMMFDXnWG+oPcI6bosyvM+I8FDqwE3VcbmFlEJPnC4hQvwK3JjAju6FGhDgoB98rihcaUlsJfoTvrSmkLAmQOH8DW+a0UVbcCMp7TtWgpC8UMT0adAb/4ngQhjYuED4pI=";
			
			        $request = new YopRequest("app_10088909942", $private_key);
			        $expireTime = date("yyyy-MM-dd HH:mm:ss", strtotime("+30 minute"));//过期时间
			        $client_ip = $_SERVER['REMOTE_ADDR'];
			        //加入请求参数
			        $request->addParam("parentMerchantNo",'10088970121');
			        $request->addParam("merchantNo",$yee['merchantNo']);
			        $request->addParam("orderId",$osn);
			        $request->addParam("orderAmount",$total_amount);
			        $request->addParam("expiredTime",$expireTime);
			        $request->addParam("notifyUrl",'https://store.leyinshuke.com/api/index/yeenotify');
			        $request->addParam("memo",'');
			        $request->addParam("goodsName",'充值订单');
			        $request->addParam("fundProcessType",'');
			        $request->addParam("payWay",'MINI_PROGRAM');
			        $request->addParam("channel", 'WECHAT');
			        $request->addParam("scene", 'OFFLINE');
			        $request->addParam("appId", $storeinfo['wx_appid']);
			        $request->addParam("userId",$userinfo['openid']);
			        $request->addParam("userIp", $client_ip);
			//      //提交Post请求
			        $response = YopRsaClient::post("/rest/v1.0/aggpay/pre-pay", $request);
			        if(isset($response->result->code) && $response->result->code == '00000')
			        {
			        	$data = json_decode($response->result->prePayTn, JSON_UNESCAPED_UNICODE);
			        	Order::where('order_no', $osn)->update(['channel'=>'YeeBao']);
		    	        Orderrecharge::where('order_no', $osn)->update(['channel'=>'YeeBao']);
			        	$this->success($response->result->message,$data);
			        }
                    $this->error('支付失败');
    		}
    		
    		if($channel['code'] == 'sandPay')
    		{
    			$sandmer = Sandmerch::where('store_no',$store_no)->find();
    			    $request = new HmPayClient();

			        $url = $request->gatewayUrl;
			
			        $appId = '552021071325659';
			        $subAppId = $sandmer['sub_merchant_no'];
			        $method = "trade.create";
			        $format = $request->format;
			        $charset = $request->charset;
			        $signType = $request->signType;
			        $version = $request->apiVersion;
			        $timestamp = date("Y-m-d h:i:s");
			        $nonce = $request->getRandStr(8);
			        $privateKey = $request->rsaPrivateKey;
			        //支付方式
			        $payWay = "WECHAT";
			        $pay_type = "JSAPI";
			        $createIp = $_SERVER['REMOTE_ADDR'];//生产环境使用真实ip
			        $createTime = date("YmdHis");
			        $expireTime = date("YmdHis", strtotime("+10 minute"));//过期时间
			        $totalAmount = $total_amount;
			        $outOrderNo = $osn;
			        //商品详情 -- 按实际填写 或不填不上送
			        $goodsDetail1 = array();
//			        $goodsDetail1['goods_id'] = $oil['id'];
//			        $goodsDetail1['goods_name'] = $oil['gas_name'];
//			        $goodsDetail1['price'] = $oil['price'];
		
			        $goodsDetail = array($goodsDetail1);
			        //订单详情
			        $body = '充值订单';
			        //商户交易门店
			        $storeId = $sandmer['sand_store_no'];
			        $mer_app_id = $storeinfo['wx_appid'];
			        $mer_buyer_id = $userinfo['openid'];
			        //终端信息
//			        $deviceInfo = array();
//			        $deviceInfo['longitude'] = '121.506377';
//			        $deviceInfo['latitude'] = '31.245105';
//			
			        $notifyUrl = 'https://store.leyinshuke.com/api/index/sandscannotify';
			
			        $bizContent = $request->tradecreate($payWay, $pay_type, $mer_app_id, $mer_buyer_id, $createIp, $createTime, $expireTime, $totalAmount, $outOrderNo, $goodsDetail, $body, $storeId, $notifyUrl);
			        
			        $response = $request->execute($url, $request->request($appId, $subAppId, $method, $format, $charset, $signType, $timestamp, $nonce, $version, $bizContent, $privateKey));
			        
			        $jsonResp = json_decode($response, JSON_UNESCAPED_UNICODE);
			        if(isset($jsonResp['code']) && $jsonResp['code'] == '200')
			        {
			        	$data = json_decode($jsonResp['data'], JSON_UNESCAPED_UNICODE);
			            $datapay = json_decode($data['pay_data'], JSON_UNESCAPED_UNICODE);
			            Order::where('order_no', $osn)->update(['channel'=>'sandPay']);
		    	        Orderrecharge::where('order_no', $osn)->update(['channel'=>'sandPay']);
			            $this->success($data['sub_msg'],$datapay);
			        }
		            $this->error('支付失败');
    		}
    	}
    	
    	
    	$this->error('支付失败');
    }
    
        
           /**
     * 单商品付款
     *
     */
    public function singlesubmit()
    {
     	$user = $this->auth->getUser();
//      $user_id = $this->request->post('user_id');
        $store_no = $this->request->post('store_no');
    	$goods_id = $this->request->post('goods_id');
    	$num = $this->request->post('num');//商品商量
    	$total_amount = $this->request->post('total_amount');//订单总额
    	$pay_type = $this->request->post('pay_type');//订单总额
    	$pay = 1;
    	if($pay_type == 'balance')$pay = 5;

    	$osn = date('YmdHis') . rand(10000000,99999999);
    	
    		$good = \app\admin\model\goods_manage\Goods::where('id',$goods_id)->find();
    		if(!$good)$this->error('商品不存在');
	        $paramgood['store_no']=$store_no;
	        $paramgood['user_id']=$user->id;
	        $paramgood['order_no']=$osn;
	        $paramgood['total_price']=$total_amount;
	        $paramgood['total_pay_price']=$total_amount;
	        $paramgood['discount_price']=0;
	        $paramgood['is_pay']=0;
	        $paramgood['pay_type']=$pay;
	        $paramgood['pay_time']=time();
	        $paramgood['source_type']=1;
	        $paramgood['pay_way']=1;
    		$resultgood = \app\admin\model\exchange\Ordergoods::create($paramgood);
    		if($resultgood)
    		{
    	
    			//订单详情
		        $paraminfo['store_no']=$store_no;
		        $paraminfo['order_id']=$resultgood['id'];
		        $paraminfo['goods_id']=$goods_id;
		        $paraminfo['num']=$num;
		        $paraminfo['unit_price']=$good['price'];
		        $paraminfo['total_price']=$total_amount;
		        $paraminfo['goods_sku']=$good['sku'];

	    		$resultinfo = \app\admin\model\exchange\OrderGoodsInfo::create($paraminfo);
	    		//录入总订单
		        $params['store_no']=$store_no;
		        $params['user_id']=$user->id;
		        $params['order_no']=$osn;
		        $params['total_price']=$total_amount;
		        $params['total_pay_price']=$total_amount;
		        $params['discount_price']=0;
		        $params['is_pay']=0;
		        $params['pay_type']=$pay;
		        $params['type']=3;
		        $params['source_type']=1;
		        $params['pay_time']=time();
		        $params['pay_way']=1;
		    
		    	$result = \app\admin\model\exchange\Order::create($params);
    		}

    	
    	if($pay_type == 'balance')
    	{
    		if($total_amount > $user->money)$this->error('余额不足');
    		
    		   	$before = $user->money;
		    	$money = $user->money - $total_amount;
		    	$user->money = $money;
                $user->save();
                $memo = $good['goods_name'];
                //写入日志
                $resultmo = \app\common\model\MoneyLog::create(['user_id' => $user->id, 'money' => $total_amount, 'before' => $before, 'after' => $money, 'memo' => $memo]);
		    	
		    	$this->success('支付成功');
    		
    	}
    	
    	if($pay_type == 'wechat')
    	{
    		$storeinfo = \app\admin\model\system_config\Storeset::where('store_no',$store_no)->find();
    		$pay= \app\admin\model\payment\Payway::where('code','wechat')->find();
    		$channel= \app\admin\model\payment\Channel::where('id',$pay['channel_id'])->find();
    		$yee= \app\admin\model\Yee::where('store_no',$store_no)->find();
    		$userinfo= \app\admin\model\Third::where('user_id',$user->id)->find();
    	
    		if($channel['code'] == 'YeeBao')
    		{
    			  /*商户私钥*/
			        $private_key ="MIIEugIBADANBgkqhkiG9w0BAQEFAASCBKQwggSgAgEAAoIBAQCQMqL/T97RhAophQNRzBwE+vU+59PzfkEzyLZwMaQTduHvdTl4fg6KZ6ATFUgECI2JLpZq3cyjVYSlM9H20bRpZSaoYmsYyNibpf2lg+bMg9G+bS6elHvFn0ZJ+aU40wyWqPjtdLB9JYLDbLVsb6SzHegWovWeWD7vUqCbPhDK24V///baX2zV4609kfa1iBGbynF/0nggHw3leeUW9F8E8twSEF15ObE8ShywOMvi578kv9PUNmSiq8gfc/t8dWVOzi4mbDje49MhxMbuopGv1kcvHBrThTeqQ2plhQSs63AbwLpe4WsZbcNvG9zpjuci8bK1+Zb/3DnkmT4zEu6FAgMBAAECggEAHsQfEPhaoztX67nslmRFSi69atmN2HMEuGbHvjJpPpnr5OqPA41pztADUG8G+Y1VnYJqJ40BX4wcjB79Wnst0hr53414KkaYKMWG0+zLrrElbErhWoZ1zhmIprn0LaaiFfchfZCbI2iAeO/V2bgMXQcxgLruSwWrD+cCS303mgBgW7tWsqlfplLvtWqJBWyA4Y8ObV/RUuLjr38Q8nCGZ81ep+De0euDkV4JQ/tg7uQEvEAOwpB6EEBwYt8GZVwcq8SWfP1cOw0Q7hkvn+rHvnXa2MHg8pdQHOfigvHr4Z5udkSiM885Pbjyh6H+UldtKFx2pW9EoD4t37CMwjeJtQKBgQDMWc00sfln9lRUBarV0D7fL6Z8/kueyBaTXFrzauHGwqK9KvB9ADmqFuBxZij8fJBkQyQtgNgbutTqgo0BJgTB2Q5lH097SBUdrTUrJdo3+rKY4/fbQBU7zF9oQ2p+dyFHmW/zjjWALnQYchd1lsZGkrSg2qPto/PRttkES/jrywKBgQC0pLrjcQ+6XZAUie+wSML+f/zGvxw1821Tn8poe0FIaX7/vPhRo028eF+R4Kav/yiVxeTAzk1D5OtN0Q3XO/nIY6f68WbdjBeFFSyovpPi1GX8kSys5wIo79nNnF/cEIJMTnvmyn51RaH8jtSVhshqqzHdesezXTYV3lwg4Urk7wKBgFqKS0ZWuIdcd76GiEuVqdWfOifVT9H5Gy+NUurY51H2OL6RwN3RdLssyaLUvcIoup0BtozGsnmOzPlegHUK0D7HGf6p4cBgjqKIdK86ZTY6SFk/YDjvarkE8xyyCgQgaklb7WM/FetGKcAPBN/fvtfT9l3yoYEQDF5Vok+qDY8DAn80N2nOVOA2/tSnGzgtvNqgtl5bFOMStUrk4Uug5//27ofHZNhiwNG3qRP3FvkX5qnUoV9+XCP5fDKIS+W0UaHiSuxDnYQehmBGF9jQ7kXRS5Qvbcd8M0psiuhqhsku05bWd9lY3S+wtnAckSziDBPiwZmoa9VOA6Oerqfy2SzNAoGAETFFK7YKO6+fGNJv5M5KJuZsOGkqgmfkJhAOnC2wLPDMMFDXnWG+oPcI6bosyvM+I8FDqwE3VcbmFlEJPnC4hQvwK3JjAju6FGhDgoB98rihcaUlsJfoTvrSmkLAmQOH8DW+a0UVbcCMp7TtWgpC8UMT0adAb/4ngQhjYuED4pI=";
			
			        $request = new YopRequest("app_10088909942", $private_key);
			        $expireTime = date("yyyy-MM-dd HH:mm:ss", strtotime("+30 minute"));//过期时间
			        $client_ip = $_SERVER['REMOTE_ADDR'];
			        //加入请求参数
			        $request->addParam("parentMerchantNo",'10088970121');
			        $request->addParam("merchantNo",$yee['merchantNo']);
			        $request->addParam("orderId",$osn);
			        $request->addParam("orderAmount",$total_amount);
			        $request->addParam("expiredTime",$expireTime);
			        $request->addParam("notifyUrl",'https://store.leyinshuke.com/api/index/yeenotify');
			        $request->addParam("memo",'');
			        $request->addParam("goodsName",$good['goods_name']);
			        $request->addParam("fundProcessType",'');
			        $request->addParam("payWay",'MINI_PROGRAM');
			        $request->addParam("channel", 'WECHAT');
			        $request->addParam("scene", 'OFFLINE');
			        $request->addParam("appId", $storeinfo['wx_appid']);
			        $request->addParam("userId",$userinfo['openid']);
			        $request->addParam("userIp", $client_ip);
			//      //提交Post请求
			        $response = YopRsaClient::post("/rest/v1.0/aggpay/pre-pay", $request);
			        if(isset($response->result->code) && $response->result->code == '00000')
			        {
			        	$data = json_decode($response->result->prePayTn, JSON_UNESCAPED_UNICODE);
			        	$this->success($response->result->message,$data);
			        }
                    $this->error('支付失败');
    		}
    		
    		if($channel['code'] == 'sandPay')
    		{
    			$sandmer = Sandmerch::where('store_no',$store_no)->find();
    			    $request = new HmPayClient();

			        $url = $request->gatewayUrl;
			
			        $appId = '552021071325659';
			        $subAppId = $sandmer['sub_merchant_no'];
			        $method = "trade.create";
			        $format = $request->format;
			        $charset = $request->charset;
			        $signType = $request->signType;
			        $version = $request->apiVersion;
			        $timestamp = date("Y-m-d h:i:s");
			        $nonce = $request->getRandStr(8);
			        $privateKey = $request->rsaPrivateKey;
			        //支付方式
			        $payWay = "WECHAT";
			        $pay_type = "JSAPI";
			        $createIp = $_SERVER['REMOTE_ADDR'];//生产环境使用真实ip
			        $createTime = date("YmdHis");
			        $expireTime = date("YmdHis", strtotime("+10 minute"));//过期时间
			        $totalAmount = $total_amount;
			        $outOrderNo = $osn;
			        //商品详情 -- 按实际填写 或不填不上送
			        $goodsDetail1 = array();
			        $goodsDetail1['goods_id'] = $good['id'];
			        $goodsDetail1['goods_name'] = $good['goods_name'];
			        $goodsDetail1['price'] = $good['price'];
		
			        $goodsDetail = array($goodsDetail1);
			        //订单详情
			        $body = $good['goods_name'];
			        //商户交易门店
			        $storeId = $sandmer['sand_store_no'];
			        $mer_app_id = $storeinfo['wx_appid'];
			        $mer_buyer_id = $userinfo['openid'];
			        //终端信息
//			        $deviceInfo = array();
//			        $deviceInfo['longitude'] = '121.506377';
//			        $deviceInfo['latitude'] = '31.245105';
//			
			        $notifyUrl = 'https://store.leyinshuke.com/api/index/sandscannotify';
			
			        $bizContent = $request->tradecreate($payWay, $pay_type, $mer_app_id, $mer_buyer_id, $createIp, $createTime, $expireTime, $totalAmount, $outOrderNo, $goodsDetail, $body, $storeId, $notifyUrl);
			        
			        $response = $request->execute($url, $request->request($appId, $subAppId, $method, $format, $charset, $signType, $timestamp, $nonce, $version, $bizContent, $privateKey));
			        
			        $jsonResp = json_decode($response, JSON_UNESCAPED_UNICODE);
			        if(isset($jsonResp['code']) && $jsonResp['code'] == '200')
			        {
			        	$data = json_decode($jsonResp['data'], JSON_UNESCAPED_UNICODE);
			            $datapay = json_decode($data['pay_data'], JSON_UNESCAPED_UNICODE);
			            $this->success($data['sub_msg'],$datapay);
			        }
		            $this->error('支付失败');
    		}
    	}
    	
    	
    	
    	$this->error('支付失败');
    }
    
    
            
           /**
     * 多商品付款
     *
     */
    public function moresubmit()
    {
     	$user = $this->auth->getUser();
//      $user_id = $this->request->post('user_id');
        $store_no = $this->request->post('store_no');
    	$goods_id = $this->request->post('goods_id');
    	$total_amount = $this->request->post('total_amount');//订单总额
    	$pay_type = $this->request->post('pay_type');//订单总额
    	$pay = 1;
    	if($pay_type == 'balance')$pay = 5;
    	
    	$goods_id = explode("-",$goods_id);

    	$osn = date('YmdHis') . rand(10000000,99999999);
//  	
//  		$good = \app\admin\model\goods_manage\Goods::where('id',$goods_id)->find();
//  		if(!$good)$this->error('商品不存在');

            $good = [];
	        $paramgood['store_no']=$store_no;
	        $paramgood['user_id']=$user->id;
	        $paramgood['order_no']=$osn;
	        $paramgood['total_price']=$total_amount;
	        $paramgood['total_pay_price']=$total_amount;
	        $paramgood['discount_price']=0;
	        $paramgood['is_pay']=0;
	        $paramgood['pay_type']=$pay;
	        $paramgood['pay_time']=time();
	        $paramgood['source_type']=1;
	        $paramgood['pay_way']=1;
    		$resultgood = \app\admin\model\exchange\Ordergoods::create($paramgood);
    		if($resultgood)
    		{
    	        if($goods_id)
    	        {
    	        	foreach ($goods_id as $in => $it) {
    	        		$goodone = \app\admin\model\goods_manage\Goods::where('id',$it)->find();
    					if(!$goodone)continue;
    					$good = $goodone;
    					$co = Cart::where('goods_id',$it)->where('store_no',$store_no)->where('user_id',$user->id)->find();
	    	        	//订单详情
				        $paraminfo['store_no']=$store_no;
				        $paraminfo['order_id']=$resultgood['id'];
				        $paraminfo['goods_id']=$it;
				        $paraminfo['num']=$co['num'];
				        $paraminfo['unit_price']=$goodone['price'];
				        $paraminfo['total_price']=$goodone['price']*$co['num'];
				        $paraminfo['goods_sku']=$goodone['sku'];
		
			    		$resultinfo = \app\admin\model\exchange\OrderGoodsInfo::create($paraminfo);
			    		
			    		//扣减商品库存

				        Goods::where('id', $it)->setDec('goods_stock', $co['num']);
				        
				        //删除购物车
				        Cart::where('goods_id',$it)->where('store_no',$store_no)->where('user_id',$user->id)->delete();
		    		}
    	        }
    			
	    		//录入总订单
		        $params['store_no']=$store_no;
		        $params['user_id']=$user->id;
		        $params['order_no']=$osn;
		        $params['total_price']=$total_amount;
		        $params['total_pay_price']=$total_amount;
		        $params['discount_price']=0;
		        $params['is_pay']=0;
		        $params['pay_type']=$pay;
		        $params['type']=3;
		        $params['source_type']=1;
		        $params['pay_time']=time();
		        $params['pay_way']=1;
		    
		    	$result = \app\admin\model\exchange\Order::create($params);
    		}

    	
    	if($pay_type == 'balance')
    	{
    		if($total_amount > $user->money)$this->error('余额不足');
    		
    		   	$before = $user->money;
		    	$money = $user->money - $total_amount;
		    	$user->money = $money;
                $user->save();
                $memo = $good['goods_name'];
                //写入日志
                $resultmo = \app\common\model\MoneyLog::create(['user_id' => $user->id, 'money' => $total_amount, 'before' => $before, 'after' => $money, 'memo' => $memo]);
		    	Order::where('order_no', $osn)->update(['is_pay'=>2]);
		    	Ordergoods::where('order_no', $osn)->update(['is_pay'=>2]);
		    	$this->success('支付成功');
    		
    	}
    	
    	if($pay_type == 'wechat')
    	{
    		$storeinfo = \app\admin\model\system_config\Storeset::where('store_no',$store_no)->find();
    		$pay= \app\admin\model\payment\Payway::where('code','wechat')->find();
    		$channel= \app\admin\model\payment\Channel::where('id',$pay['channel_id'])->find();
    		$yee= \app\admin\model\Yee::where('store_no',$store_no)->find();
    		$userinfo= \app\admin\model\Third::where('user_id',$user->id)->find();
    	
    		if($channel['code'] == 'YeeBao')
    		{
    			  /*商户私钥*/
			        $private_key ="MIIEugIBADANBgkqhkiG9w0BAQEFAASCBKQwggSgAgEAAoIBAQCQMqL/T97RhAophQNRzBwE+vU+59PzfkEzyLZwMaQTduHvdTl4fg6KZ6ATFUgECI2JLpZq3cyjVYSlM9H20bRpZSaoYmsYyNibpf2lg+bMg9G+bS6elHvFn0ZJ+aU40wyWqPjtdLB9JYLDbLVsb6SzHegWovWeWD7vUqCbPhDK24V///baX2zV4609kfa1iBGbynF/0nggHw3leeUW9F8E8twSEF15ObE8ShywOMvi578kv9PUNmSiq8gfc/t8dWVOzi4mbDje49MhxMbuopGv1kcvHBrThTeqQ2plhQSs63AbwLpe4WsZbcNvG9zpjuci8bK1+Zb/3DnkmT4zEu6FAgMBAAECggEAHsQfEPhaoztX67nslmRFSi69atmN2HMEuGbHvjJpPpnr5OqPA41pztADUG8G+Y1VnYJqJ40BX4wcjB79Wnst0hr53414KkaYKMWG0+zLrrElbErhWoZ1zhmIprn0LaaiFfchfZCbI2iAeO/V2bgMXQcxgLruSwWrD+cCS303mgBgW7tWsqlfplLvtWqJBWyA4Y8ObV/RUuLjr38Q8nCGZ81ep+De0euDkV4JQ/tg7uQEvEAOwpB6EEBwYt8GZVwcq8SWfP1cOw0Q7hkvn+rHvnXa2MHg8pdQHOfigvHr4Z5udkSiM885Pbjyh6H+UldtKFx2pW9EoD4t37CMwjeJtQKBgQDMWc00sfln9lRUBarV0D7fL6Z8/kueyBaTXFrzauHGwqK9KvB9ADmqFuBxZij8fJBkQyQtgNgbutTqgo0BJgTB2Q5lH097SBUdrTUrJdo3+rKY4/fbQBU7zF9oQ2p+dyFHmW/zjjWALnQYchd1lsZGkrSg2qPto/PRttkES/jrywKBgQC0pLrjcQ+6XZAUie+wSML+f/zGvxw1821Tn8poe0FIaX7/vPhRo028eF+R4Kav/yiVxeTAzk1D5OtN0Q3XO/nIY6f68WbdjBeFFSyovpPi1GX8kSys5wIo79nNnF/cEIJMTnvmyn51RaH8jtSVhshqqzHdesezXTYV3lwg4Urk7wKBgFqKS0ZWuIdcd76GiEuVqdWfOifVT9H5Gy+NUurY51H2OL6RwN3RdLssyaLUvcIoup0BtozGsnmOzPlegHUK0D7HGf6p4cBgjqKIdK86ZTY6SFk/YDjvarkE8xyyCgQgaklb7WM/FetGKcAPBN/fvtfT9l3yoYEQDF5Vok+qDY8DAn80N2nOVOA2/tSnGzgtvNqgtl5bFOMStUrk4Uug5//27ofHZNhiwNG3qRP3FvkX5qnUoV9+XCP5fDKIS+W0UaHiSuxDnYQehmBGF9jQ7kXRS5Qvbcd8M0psiuhqhsku05bWd9lY3S+wtnAckSziDBPiwZmoa9VOA6Oerqfy2SzNAoGAETFFK7YKO6+fGNJv5M5KJuZsOGkqgmfkJhAOnC2wLPDMMFDXnWG+oPcI6bosyvM+I8FDqwE3VcbmFlEJPnC4hQvwK3JjAju6FGhDgoB98rihcaUlsJfoTvrSmkLAmQOH8DW+a0UVbcCMp7TtWgpC8UMT0adAb/4ngQhjYuED4pI=";
			
			        $request = new YopRequest("app_10088909942", $private_key);
			        $expireTime = date("yyyy-MM-dd HH:mm:ss", strtotime("+30 minute"));//过期时间
			        $client_ip = $_SERVER['REMOTE_ADDR'];
			        //加入请求参数
			        $request->addParam("parentMerchantNo",'10088970121');
			        $request->addParam("merchantNo",$yee['merchantNo']);
			        $request->addParam("orderId",$osn);
			        $request->addParam("orderAmount",$total_amount);
			        $request->addParam("expiredTime",$expireTime);
			        $request->addParam("notifyUrl",'https://store.leyinshuke.com/api/index/yeenotify');
			        $request->addParam("memo",'');
			        $request->addParam("goodsName",$good['goods_name']);
			        $request->addParam("fundProcessType",'');
			        $request->addParam("payWay",'MINI_PROGRAM');
			        $request->addParam("channel", 'WECHAT');
			        $request->addParam("scene", 'OFFLINE');
			        $request->addParam("appId", $storeinfo['wx_appid']);
			        $request->addParam("userId",$userinfo['openid']);
			        $request->addParam("userIp", $client_ip);
			//      //提交Post请求
			        $response = YopRsaClient::post("/rest/v1.0/aggpay/pre-pay", $request);
			        if(isset($response->result->code) && $response->result->code == '00000')
			        {
			        	$data = json_decode($response->result->prePayTn, JSON_UNESCAPED_UNICODE);
			        	Order::where('order_no', $osn)->update(['channel'=>'YeeBao']);
		    	        Ordergoods::where('order_no', $osn)->update(['channel'=>'YeeBao']);
			        	$this->success($response->result->message,$data);
			        }
                    $this->error('支付失败');
    		}
    		
    		if($channel['code'] == 'sandPay')
    		{
    			$sandmer = Sandmerch::where('store_no',$store_no)->find();
    			    $request = new HmPayClient();

			        $url = $request->gatewayUrl;
			
			        $appId = '552021071325659';
			        $subAppId = $sandmer['sub_merchant_no'];
			        $method = "trade.create";
			        $format = $request->format;
			        $charset = $request->charset;
			        $signType = $request->signType;
			        $version = $request->apiVersion;
			        $timestamp = date("Y-m-d h:i:s");
			        $nonce = $request->getRandStr(8);
			        $privateKey = $request->rsaPrivateKey;
			        //支付方式
			        $payWay = "WECHAT";
			        $pay_type = "JSAPI";
			        $createIp = $_SERVER['REMOTE_ADDR'];//生产环境使用真实ip
			        $createTime = date("YmdHis");
			        $expireTime = date("YmdHis", strtotime("+10 minute"));//过期时间
			        $totalAmount = $total_amount;
			        $outOrderNo = $osn;
			        //商品详情 -- 按实际填写 或不填不上送
			        $goodsDetail1 = array();
			        $goodsDetail1['goods_id'] = $good['id'];
			        $goodsDetail1['goods_name'] = $good['goods_name'];
			        $goodsDetail1['price'] = $good['price'];
		
			        $goodsDetail = array($goodsDetail1);
			        //订单详情
			        $body = $good['goods_name'];
			        //商户交易门店
			        $storeId = $sandmer['sand_store_no'];
			        $mer_app_id = $storeinfo['wx_appid'];
			        $mer_buyer_id = $userinfo['openid'];
			        //终端信息
//			        $deviceInfo = array();
//			        $deviceInfo['longitude'] = '121.506377';
//			        $deviceInfo['latitude'] = '31.245105';
//			
			        $notifyUrl = 'https://store.leyinshuke.com/api/index/sandscannotify';
			
			        $bizContent = $request->tradecreate($payWay, $pay_type, $mer_app_id, $mer_buyer_id, $createIp, $createTime, $expireTime, $totalAmount, $outOrderNo, $goodsDetail, $body, $storeId, $notifyUrl);
			        
			        $response = $request->execute($url, $request->request($appId, $subAppId, $method, $format, $charset, $signType, $timestamp, $nonce, $version, $bizContent, $privateKey));
			        
			        $jsonResp = json_decode($response, JSON_UNESCAPED_UNICODE);
			        if(isset($jsonResp['code']) && $jsonResp['code'] == '200')
			        {
			        	$data = json_decode($jsonResp['data'], JSON_UNESCAPED_UNICODE);
			            $datapay = json_decode($data['pay_data'], JSON_UNESCAPED_UNICODE);
			            Order::where('order_no', $osn)->update(['channel'=>'sandPay']);
		    	        Ordergoods::where('order_no', $osn)->update(['channel'=>'sandPay']);
			            $this->success($data['sub_msg'],$datapay);
			        }
		            $this->error('支付失败');
			        
    		}
    	}
    	
    	
    	
    	$this->error('支付失败');
    }
    
    
    
           /**
     * 提交订单
     *
     */
    public function submit()
    {
     	$user = $this->auth->getUser();
        $store_no = $this->request->post('store_no');
    	$type = $this->request->post('type');//2加油  3 商品
    	$goods_id = $this->request->post('goods_id');
    	$num = $this->request->post('num');//商品商量
    	$total_amount = $this->request->post('total_amount');//订单总额
    	$pay_type = $this->request->post('pay_type');//订单总额
    	$gas_id = $this->request->post('gas_id');
    	$gas_gun_id = $this->request->post('gas_gun_id');
//  	$store_no = 1;
//  	$type = 2;//2加油  3 商品
//  	$goods_id = 1;
//  	$num = 1;//商品商量
//  	$total_amount = 100;//订单总额
//  	$pay_type = 1;//订单总额
//  	$money = 200;
//  	$gas_id= 1;
//  	$gas_gun_id= 1;
//  	if($pay_type == 1&&$total_amount > $user->money)$this->error('余额不足');
    	$osn = date('YmdHis') . rand(10000000,99999999);
    	if($type == 2)
    	{
    		$oil = \app\admin\model\gas\Gasset::where('id',$gas_id)->find();
    		if(!$oil)$this->error('油号不存在');
    		$paramgas['agent_id']=1;
	        $paramgas['store_no']=1;
	        $paramgas['user_id']=$user->id;
	        $paramgas['order_no']=$osn;
	        $paramgas['total_price']=$total_amount;
	        $paramgas['total_pay_price']=$total_amount;
	        $paramgas['discount_price']=0;
	        $paramgas['is_pay']=2;
	        $paramgas['pay_type']=$pay_type;
	        $paramgas['pay_time']=time();
	        $paramgas['source_type']=1;
    		$resultgas = \app\admin\model\exchange\Ordergas::create($paramgas);
    		if($resultgas)
    		{
    			$num = round($total_amount/$oil['price'],2);
    			//订单详情
    			$paraminfo['agent_id']=1;
		        $paraminfo['store_no']=1;
		        $paraminfo['order_id']=$resultgas['id'];
		        $paraminfo['gas_gun_id']=$gas_gun_id;
		        $paraminfo['num']=$num;
		        $paraminfo['unit_price']=$oil['price'];
		        $paraminfo['total_price']=$total_amount;
		        $paraminfo['unit']=$oil['unit'];

	    		$resultinfo = \app\admin\model\exchange\OrderGasInfo::create($paraminfo);
	    		//录入总订单
	    		$params['agent_id']=1;
		        $params['store_no']=1;
		        $params['user_id']=$user->id;
		        $params['order_no']=$osn;
		        $params['total_price']=$total_amount;
		        $params['total_pay_price']=$total_amount;
		        $params['discount_price']=0;
		        $params['is_pay']=2;
		        $params['pay_type']=$pay_type;
		        $params['type']=$type;
		        $params['source_type']=1;
		        $params['pay_time']=time();
		    
		    	$result = \app\admin\model\exchange\Order::create($params);
//		    	$before = $user->money;
//		    	$money = $user->money - $total_amount;
//		    	$user->money = $money;
//              $user->save();
//              $memo = '油品下单';
//              //写入日志
//              $resultmo = \app\common\model\MoneyLog::create(['user_id' => $user->id, 'money' => $total_amount, 'before' => $before, 'after' => $money, 'memo' => $memo]);
//		    	
//		    	$this->success('支付成功');
    		}
    		
//  		$this->error('支付失败');
    	}
    	if($type == 3)
    	{
    		$good = \app\admin\model\goods_manage\Goods::where('id',$goods_id)->find();
    		if(!$good)$this->error('商品不存在');
    		$paramgood['agent_id']=1;
	        $paramgood['store_no']=1;
	        $paramgood['user_id']=$user->id;
	        $paramgood['order_no']=$osn;
	        $paramgood['total_price']=$total_amount;
	        $paramgood['total_pay_price']=$total_amount;
	        $paramgood['discount_price']=0;
	        $paramgood['is_pay']=2;
	        $paramgood['pay_type']=$pay_type;
	        $paramgood['pay_time']=time();
	        $paramgood['source_type']=1;
    		$resultgood = \app\admin\model\exchange\Ordergoods::create($paramgood);
    		if($resultgood)
    		{
    	
    			//订单详情
    			$paraminfo['agent_id']=1;
		        $paraminfo['store_no']=1;
		        $paraminfo['order_id']=$resultgood['id'];
		        $paraminfo['goods_id']=$goods_id;
		        $paraminfo['num']=$num;
		        $paraminfo['unit_price']=$good['price'];
		        $paraminfo['total_price']=$total_amount;
		        $paraminfo['goods_sku']=$good['sku'];

	    		$resultinfo = \app\admin\model\exchange\OrderGoodsInfo::create($paraminfo);
	    		//录入总订单
	    		$params['agent_id']=1;
		        $params['store_no']=1;
		        $params['user_id']=$user->id;
		        $params['order_no']=$osn;
		        $params['total_price']=$total_amount;
		        $params['total_pay_price']=$total_amount;
		        $params['discount_price']=0;
		        $params['is_pay']=2;
		        $params['pay_type']=$pay_type;
		        $params['type']=$type;
		        $params['source_type']=1;
		        $params['pay_time']=time();
		    
		    	$result = \app\admin\model\exchange\Order::create($params);
//		    	$before = $user->money;
//		    	$money = $user->money - $total_amount;
//		    	$user->money = $money;
//              $user->save();
//              $memo = '商品下单';
//              //写入日志
//              $resultmo = \app\common\model\MoneyLog::create(['user_id' => $user->id, 'money' => $total_amount, 'before' => $before, 'after' => $money, 'memo' => $memo]);
//		    	
//		    	$this->success('支付成功');
    		}
    		
//  		$this->error('支付失败');
    	}
    	
    	if($pay_type == 'balance')
    	{
    		if($total_amount > $user->money)$this->error('余额不足');
    		
    		   	$before = $user->money;
		    	$money = $user->money - $total_amount;
		    	$user->money = $money;
                $user->save();
//              $memo = '商品下单';
                //写入日志
                $resultmo = \app\common\model\MoneyLog::create(['user_id' => $user->id, 'money' => $total_amount, 'before' => $before, 'after' => $money, 'memo' => $memo]);
		    	
		    	$this->success('支付成功');
    		
    	}
    	
    	if($pay_type == 'wechat')
    	{
    		$pay= \app\admin\model\payment\Payway::where('code','wechat')->find();
    		$channel= \app\admin\model\payment\Channel::where('id',$pay['channel_id'])->find();
    		if($channel['code'] == 'YeeBao')
    		{
    			
    		}
    		
    		if($channel['code'] == 'sandPay')
    		{
    			
    		}
    	}
    	
    	
    	$this->error('支付失败');
    }
    
      /**
     * 获取优惠金额
     *
     * @ApiMethod (POST)
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function getDiscount()
    {
    	$user = $this->auth->getUser();
    	$user_id = $this->request->post("user_id");
        $store_no = $this->request->post("store_no");
        $gas_id = $this->request->post("gas_id");
        $type = $this->request->post("type");//1油品  2 商品
        $total_amount = $this->request->post("total_amount");
        $discount_price = 0;
        $is_setcou = StoreConfig::where('name','is_setcou')->where('store_no',$store_no)->find();
        $coupon_type = StoreConfig::where('name','coupon_type')->where('store_no',$store_no)->find();
        if(($type == 2||$type == 1)&&$is_setcou['value'] == 1)
        {
        	$timebool = true;
	    	$llimitoil = StoreConfig::where('name','oil')->where('store_no',$store_no)->find();
	    	$llimittime = StoreConfig::where('name','oil_times')->where('store_no',$store_no)->find();
	    	$storeset = StoreConfig::where('name','awardoil')->where('store_no',$store_no)->find();
	    	$limituser = StoreConfig::where('name','user_nolimit')->where('store_no',$store_no)->find();
	    
	    	if(!empty($llimitoil['value']))
	    	{
	    		$oilarr = explode(',',$llimitoil['value']);
	    		$amount = json_decode($storeset['value'],true);
	    		$userarr = explode(',',$limituser['value']);
	    		if(!empty($llimittime['value']))
	    	    {
	    	    	$limittime =  strtotime('-'.$llimittime['value'].' hours');
	    	    	$is_order = Ordergas::where('createtime','>',$limittime)->where('is_pay',2)->where('user_id',$user_id)->where('discount_price','>',0)->where('store_no',$store_no)->count();
	    	        if($is_order)$timebool = false;
	    	      
	    	    }
	    	    if(in_array($user_id,$userarr))
		    	{
		    		$timebool = true;
		    	}
	    		if(in_array($gas_id,$oilarr)&&!empty($amount)&&$timebool&&$coupon_type['value']==1)
	    		{
	    			foreach ($amount as $k => $v) {
		    			if($total_amount >=$k&&$discount_price<$v)$discount_price = $v;
		    		}
	 	    		$this->success('获取成功',round($discount_price,2));
	    		}
	    		
	    		if(in_array($gas_id,$oilarr)&&!empty($amount)&&$timebool&&$coupon_type['value']==2)
	    		{
	    			$amco = count($amount);
	    			$oil = \app\admin\model\gas\Gasset::where('id',$gas_id)->find();
	    			//升数
	    			$num = round($total_amount/$oil['price'],2);
	    			$i = 1;
	    			$boins = 0;
	    			$kamount = 0;
	    			foreach ($amount as $k => $v) {
	    				if($total_amount >=$k)$discount_price = round($num*$v,2);
//	    				if($amco == 1&&$total_amount>=$k)$discount_price = round($num*$v,2);
//	    		
//		    			if($amco > 1)
//		    			{
//		    				if($i==1&&$total_amount<$k)break;
//		    				if($i>1&&$total_amount>=$k)
//		    				{
//		    					if($i == 2)$fnum = round($k/$oil['price'],2);
//		    					if($i > 2)$fnum = round(($k-$kamount)/$oil['price'],2);	
//		    					$fprice = round($fnum*$boins,2);
//		    					$discount_price = $discount_price + $fprice;
//		    					
//		    					if($amco == $i)
//		    					{
//		    						$fnum = round(($total_amount-$k)/$oil['price'],2);	
//			    					$fprice = round($fnum*$v,2);
//			    					$discount_price = $discount_price + $fprice;
//		    					}
//		    				}
//		    				
//		    				if($i>2&&$total_amount<$k)
//		    				{
//		    						$fnum = round(($total_amount-$kamount)/$oil['price'],2);
//		    						$fprice = round($fnum*$boins,2);
//		    						$discount_price = $discount_price + $fprice;
//		    						break;
//		    				}
//		    				
//		    				if($i==2&&$total_amount<$k)
//		    				{
//		    						$fnum = round($total_amount/$oil['price'],2);
//		    						
//		    						$fprice = round($fnum*$boins,2);
//		    						$discount_price = $discount_price + $fprice;
//		    						break;
//		    				}
//		    			}
//		    			$kamount = $k;
//		    			$boins = $v;
//		    			$i++;
		    		}
		    		$this->success('获取成功',round($discount_price,2));
	    		}
	    	
	    	}
        }
    	
        $this->success('获取成功',round($discount_price,2));
    }
    
}
